package com.trw.trp.filter;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.trw.trp.util.TRPConstants;

public class AuthInterceptor extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8756653841986699035L;
	public static final String GOING_TO_URL_KEY = "GOING_TO";

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext actionContext = invocation.getInvocationContext();
		Map<String, Object> session = actionContext.getSession();
		if (session != null && session.get(TRPConstants.CURRENT_USER) != null) {
			return invocation.invoke();
		}
		setGoingToURL(session, invocation);
		return "login";
	}

	private void setGoingToURL(Map<String, Object> session,
			ActionInvocation invocation) {
		String url = "";
		String namespace = invocation.getProxy().getNamespace();
		if (StringUtils.isNotBlank(namespace) && !namespace.equals("/")) {
			url = url + namespace;
		}
		String actionName = invocation.getProxy().getActionName();
		if (StringUtils.isNotBlank(actionName)) {
			HttpServletRequest request = ServletActionContext.getRequest();
			url = request.getRequestURL().toString();
			if (request.getQueryString() != null) {
				url += "?" + request.getQueryString();
			}
		}
		session.put(GOING_TO_URL_KEY, url);
	}

}
